package org.chench.extra;

import java.io.*;
import java.net.InetSocketAddress;
import java.net.Socket;

/**
 * 验证使用普通Socket是否能与ZMQ服务端通通信
 * @author chench9@lenovo.com
 * @desc org.chench.extra.HelloWorldCommonClient
 * @date 3/20/19 2:46 PM
 */
public class HelloWorldCommonClient {
    public static void main(String[] args) throws IOException {
        startClient();
    }

    // 结果: 无法使用普通Socket与ZMQ服务端通信
    private static void startClient() throws IOException {
        Socket socket = new Socket();
        socket.connect(new InetSocketAddress("localhost", 5555));
        InputStream is = socket.getInputStream();
        OutputStream out = socket.getOutputStream();

        // 连接服务器
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        String line = null;
        while((line = reader.readLine()) != null) {
            // 先发送请求
            out.write(line.getBytes());
            System.out.println("send: " + line);

            // 再接收数据
            byte[] buffer = new byte[128];
            int number = 0;
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            while((number = is.read(buffer)) > 0) {
                bos.write(buffer, 0, number);
            }
            System.out.println("Received: [" + new String(bos.toByteArray()) + "]");
        }
    }
}
